package cn.phecda.boot.tenant.test.table.jpa;

import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p> TODO </p>
 *
 * @author : wanpinwei
 */
@Service
@RequiredArgsConstructor
public class PersonTenantJpaService {
    private final PersonTenantJpaRepository personTenantJpaRepository;

    @Async
    @Transactional
    @SneakyThrows
    public void asyncSave(String name) {
        TimeUnit.SECONDS.sleep(3);
        personTenantJpaRepository.save(personTenantJpaRepository.named(name));
    }

    @Transactional
    public PersonTenantJpaEntity save(String name) {
        return personTenantJpaRepository.save(personTenantJpaRepository.named(name));
    }

    @Transactional
    public void update(String id, String name) {
        personTenantJpaRepository.findById(id).ifPresent(person -> {
            person.setName(name);
            personTenantJpaRepository.save(person);
        });
    }

    @Transactional
    public void delete(String id) {
        personTenantJpaRepository.deleteById(id);
    }

    public List<PersonTenantJpaEntity> findAll() {
        return personTenantJpaRepository.findAll();
    }

    public PersonTenantJpaEntity findById(String id) {
        return personTenantJpaRepository.findById(id).orElse(null);
    }
}
